package com.itheima.springbootwebtlias.service.impl;

import com.itheima.springbootwebtlias.anno.LogOperation;
import com.itheima.springbootwebtlias.exception.DeletionIsNotAllowed;
import com.itheima.springbootwebtlias.mapper.DeptMapper;
import com.itheima.springbootwebtlias.pojo.Dept;
import com.itheima.springbootwebtlias.service.DeptService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 部门业务层实现类：处理部门相关业务逻辑
 */
@Slf4j
@Service
public class DeptServiceImpl implements DeptService {

    @Autowired
    private DeptMapper deptMapper;

    //查询所有部门
    @Override
    public List<Dept> selectAll() {
        List<Dept> depts = deptMapper.selectAll();
        return depts;
    }

    //删除部门,
    @LogOperation
    @Override
    public void removeById(Integer id) {
        //查询当前部门是否存在员工
        //如果存在员工，则不允许删除,定义查询员工数量方法
        Integer count = deptMapper.selectCountByDeptId(id);
        if (count != 0) {
            //不允许删除
            throw new DeletionIsNotAllowed("当前部门存在员工，不允许删除！");
        }
        deptMapper.removeById(id);
    }

    //新增部门数据
    @LogOperation
    @Override
    public void saveDept(Dept dept) {
        //设置创建时间、更新时间
        dept.setCreateTime(LocalDateTime.now());
        dept.setUpdateTime(LocalDateTime.now());
        deptMapper.saveDept(dept);
    }

    //     根据id查询部门数据
    @Override
    public Dept findById(Integer id) {
        return deptMapper.selectById(id);
    }

    //     修改部门数据
    @Override
    @LogOperation
    public void update(Dept dept) {
        //1.同步更新时间
        dept.setUpdateTime(LocalDateTime.now());

        //2.调用mapper层修改部门数据
        deptMapper.update(dept);
    }

}
